using System;
using Csla;
using System.Data;
using Csla.Data;
using ENT.GP.Datos.MysqlHelper;

namespace ENT.GP.Core
{
    /// <summary>
    /// Estereotipo: EditableRoot
    /// Reponsabilidad: Diana
    /// Fecha: 
    /// </summary>
    [Serializable]
    public class Empresas : BusinessBase<Empresas>
    {
        #region Business Methods

        #region < CLAVE PRIMARIA >

        // Identificador
        private static PropertyInfo<int> IdProperty = RegisterProperty<int>(o => o.Id);
        /// <summary>
        /// Identificador de Catalogo
        /// </summary>
        public int Id
        {
            get { return GetProperty(IdProperty); }
        }

        #endregion

        #region < PROPIEDADES >
        
        private static PropertyInfo<string> NombreProperty = RegisterProperty<string>(o => o.Nombre, "Name");
        public string Nombre
        {
            get { return GetProperty(NombreProperty); }
            set { SetProperty(NombreProperty, value); }
        }

        private static PropertyInfo<string> DescripcionProperty = RegisterProperty<string>(o => o.Descripcion, "Name");
        public string Descripcion
        {
            get { return GetProperty(DescripcionProperty); }
            set { SetProperty(DescripcionProperty, value); }
        }
        private static PropertyInfo<string> CodigoProperty = RegisterProperty<string>(o => o.Codigo, "Name");
        public string Codigo
        {
            get { return GetProperty(CodigoProperty); }
            set { SetProperty(CodigoProperty, value); }
        }
        private static PropertyInfo<string> UrlLogoProperty = RegisterProperty<string>(o => o.UrlLogo, "Name");
        public string UrlLogo
        {
            get { return GetProperty(UrlLogoProperty); }
            set { SetProperty(UrlLogoProperty, value); }
        }
        private static PropertyInfo<int> EstadoProperty = RegisterProperty<int>(o => o.Estado, "Name");
        public int Estado
        {
            get { return GetProperty(EstadoProperty); }
            set { SetProperty(EstadoProperty, value); }
        }
       

        #endregion              

        public static bool VerificarNombre(string sNombre)
        {
            return ExisteEmpresaCommand.Execute(sNombre);
        }
        public static bool VerificarCodigo(string sCodigo)
        {
            return ExisteCodigoCommand.Execute(sCodigo);
        }


        #endregion

        #region Validation Rules

        protected override void AddBusinessRules()
        {
            // TODO: add validation rules
            //ValidationRules.AddRule(RuleMethod, "");
        }

        #endregion

        #region Authorization Rules

        protected override void AddAuthorizationRules()
        {
            // TODO: add authorization rules
            //AuthorizationRules.AllowWrite("Name", "Role");
        }

        private static void AddObjectAuthorizationRules()
        {
            // TODO: add authorization rules
            //AuthorizationRules.AllowEdit(typeof(Catalogo), "Role");
        }

        #endregion

        #region Factory Methods

        public static Empresas New()
        {
            return DataPortal.Create<Empresas>();
        }

        public static Empresas Get(int id)
        {
            return DataPortal.Fetch<Empresas>(
              new SingleCriteria<Empresas, int>(id));
        }

        public static void Delete(int id)
        {
            DataPortal.Delete(new SingleCriteria<Empresas, int>(id));
        }

        private Empresas()
        { /* Require use of factory methods */ }

        #endregion

        #region Data Access

        [RunLocal]
        protected override void DataPortal_Create()
        {
            
                base.DataPortal_Create();
            
        }

        private void DataPortal_Fetch(SingleCriteria<Empresas, int> criteria)
        {
            DataSet dsDatos = new DataSet();
            HelperMySql objhm = HelperMySql.ObtenerConexion("");
            MySql.Data.MySqlClient.MySqlParameter[] parametros = new MySql.Data.MySqlClient.MySqlParameter[1];
            parametros[0] = new MySql.Data.MySqlClient.MySqlParameter("ID", criteria.Value);
            dsDatos = objhm.EjecutarStoreProcedure(parametros, "Obtener_Empresa");
            if (dsDatos.Tables[0].Rows.Count > 0)
            {
                LoadProperty(IdProperty, Convert.ToInt32(dsDatos.Tables[0].Rows[0][0].ToString()));
                LoadProperty(NombreProperty, dsDatos.Tables[0].Rows[0][1].ToString());
                LoadProperty(DescripcionProperty, dsDatos.Tables[0].Rows[0][2].ToString());
                LoadProperty(CodigoProperty, dsDatos.Tables[0].Rows[0][3].ToString());
                LoadProperty(UrlLogoProperty, dsDatos.Tables[0].Rows[0][4].ToString());

                LoadProperty(EstadoProperty, Convert.ToInt32(dsDatos.Tables[0].Rows[0][5].ToString()));
            }
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_Insert()
        {
            HelperMySql objhm = HelperMySql.ObtenerConexion("");
            MySql.Data.MySqlClient.MySqlParameter[] parametros = new MySql.Data.MySqlClient.MySqlParameter[5];
            
            parametros[0] = new MySql.Data.MySqlClient.MySqlParameter("NOMBRE1", Nombre );
            parametros[1] = new MySql.Data.MySqlClient.MySqlParameter("DESCRI1", Descripcion );
            parametros[2] = new MySql.Data.MySqlClient.MySqlParameter("CODIGO1",Codigo);
            parametros[3] = new MySql.Data.MySqlClient.MySqlParameter("URL1", UrlLogo);
            parametros[4] = new MySql.Data.MySqlClient.MySqlParameter("ESTADO1",Estado);
            objhm.EjecutarStoreProcedure("Insertar_Empresa", parametros);
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_Update()
        {
            HelperMySql objhm = HelperMySql.ObtenerConexion("");
            MySql.Data.MySqlClient.MySqlParameter[] parametros = new MySql.Data.MySqlClient.MySqlParameter[5];
            parametros[0] = new MySql.Data.MySqlClient.MySqlParameter("ID", Id);
            parametros[1] = new MySql.Data.MySqlClient.MySqlParameter("NOMBRE1", Nombre);
            parametros[2] = new MySql.Data.MySqlClient.MySqlParameter("DESCRI1", Descripcion);
            parametros[3] = new MySql.Data.MySqlClient.MySqlParameter("URL1", UrlLogo);
            parametros[4] = new MySql.Data.MySqlClient.MySqlParameter("ESTADO1", Estado);
            objhm.EjecutarStoreProcedure("Actualizar_Empresa", parametros);
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_DeleteSelf()
        {
            
                DataPortal_Delete(new SingleCriteria<Empresas, int>(ReadProperty(IdProperty)));
            
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        private void DataPortal_Delete(SingleCriteria<Empresas, int> criteria)
        {
            HelperMySql objhm = HelperMySql.ObtenerConexion("");
            MySql.Data.MySqlClient.MySqlParameter[] parametros = new MySql.Data.MySqlClient.MySqlParameter[1];
            
            parametros[0] = new MySql.Data.MySqlClient.MySqlParameter("ID", Id);
            objhm.EjecutarStoreProcedure("Eliminar_Empresa", parametros);
       }

        #endregion
    }

    [Serializable]
    public class ExisteEmpresaCommand : CommandBase
    {
        private string _codigo;

        #region Authorization Methods

        public static bool CanExecuteCommand()
        {
            // TODO: customize to check user role
            //return Csla.ApplicationContext.User.IsInRole("Role");
            return true;
        }

        #endregion

        #region Factory Methods

        public static bool Execute(string codigo)
        {
            if (!CanExecuteCommand())
                throw new System.Security.SecurityException("Not authorized to execute command");

            ExisteEmpresaCommand cmd = new ExisteEmpresaCommand(codigo);
            cmd.BeforeServer();
            cmd = DataPortal.Execute<ExisteEmpresaCommand>(cmd);
            cmd.AfterServer();
            return cmd.Result;
        }

        private ExisteEmpresaCommand(string codigo)
        {
            /* require use of factory methods */
            _codigo = codigo;
            _result = false;
        }

        #endregion

        #region Client-side Code

        // TODO: add your own fields and properties
        bool _result;

        public bool Result
        {
            get { return _result; }
        }

        private void BeforeServer()
        {
            // TODO: implement code to run on client
            // before server is called
        }

        private void AfterServer()
        {
            // TODO: implement code to run on client
            // after server is called
        }

        #endregion

        #region Server-side Code

        protected override void DataPortal_Execute()
        {
            int numeroUsuario = 0;
            object valret;
            HelperMySql objhm = HelperMySql.ObtenerConexion("");
            MySql.Data.MySqlClient.MySqlParameter[] parametros = new MySql.Data.MySqlClient.MySqlParameter[1];
            try
            {

                parametros[0] = new MySql.Data.MySqlClient.MySqlParameter("NOMBRE1", _codigo);
                valret = objhm.EjecutarStoreProcedure("Comprobar_Empresa", parametros, 1);
                int.TryParse(valret.ToString(), out numeroUsuario);
                if (numeroUsuario == 0)
                    _result = false;
                else

                    _result = true;

            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion
    }
    [Serializable]
    public class ExisteCodigoCommand : CommandBase
    {
        private string _codigo;

        #region Authorization Methods

        public static bool CanExecuteCommand()
        {
            // TODO: customize to check user role
            //return Csla.ApplicationContext.User.IsInRole("Role");
            return true;
        }

        #endregion

        #region Factory Methods

        public static bool Execute(string codigo)
        {
            if (!CanExecuteCommand())
                throw new System.Security.SecurityException("Not authorized to execute command");

            ExisteCodigoCommand cmd = new ExisteCodigoCommand(codigo);
            cmd.BeforeServer();
            cmd = DataPortal.Execute<ExisteCodigoCommand>(cmd);
            cmd.AfterServer();
            return cmd.Result;
        }

        private ExisteCodigoCommand(string codigo)
        {
            /* require use of factory methods */
            _codigo = codigo;
            _result = false;
        }

        #endregion

        #region Client-side Code

        // TODO: add your own fields and properties
        bool _result;

        public bool Result
        {
            get { return _result; }
        }

        private void BeforeServer()
        {
            // TODO: implement code to run on client
            // before server is called
        }

        private void AfterServer()
        {
            // TODO: implement code to run on client
            // after server is called
        }

        #endregion

        #region Server-side Code

        protected override void DataPortal_Execute()
        {
            int numeroUsuario = 0;
            object valret;
            HelperMySql objhm = HelperMySql.ObtenerConexion("");
            MySql.Data.MySqlClient.MySqlParameter[] parametros = new MySql.Data.MySqlClient.MySqlParameter[1];
            try
            {

                parametros[0] = new MySql.Data.MySqlClient.MySqlParameter("codigo", _codigo);
                valret = objhm.EjecutarStoreProcedure("Comprobar_Codigo_Empresa", parametros, 1);
                int.TryParse(valret.ToString(), out numeroUsuario);
                if (numeroUsuario == 0)
                    _result = false;
                else

                    _result = true;

            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion
    }

}